﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Net;

namespace AuthenticationDemo.TokenValidation
{
    public class CustomJwtBearerEvents : JwtBearerEvents
    {

        /// <summary>
        /// 验证之前
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task MessageReceived(MessageReceivedContext context)
        {
            //默认情况：验证的token是从请求头中的【authorization】获取，不要Bearer
            var authorizationIsHave = context.Request.Headers.ContainsKey("Authorization");
            string authorization = context.Request.Headers["Authorization"].ToString();
            // "Bearer " --> Bearer后面跟一个空格
            string token = authorization.StartsWith("Bearer ") ? authorization.Remove(0, "Bearer ".Length) : authorization;
            if (authorizationIsHave)
                context.Token = token;
            return base.MessageReceived(context);
        }

        /// <summary>
        /// 验证通过但权限不足
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        //public override Task Forbidden(ForbiddenContext context)
        //{
        //    return Task.CompletedTask;
        //}

        /// <summary>
        /// 验证失败，如token格式不正确
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        //public override Task Challenge(JwtBearerChallengeContext context)
        //{
        //    return Task.CompletedTask;
        //}

        /// <summary>
        /// 验证通过
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        //public override Task TokenValidated(TokenValidatedContext context)
        //{
        //    return Task.CompletedTask;
        //}

        /// <summary>
        /// 在处理请求期间引发异常时调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        //public override Task AuthenticationFailed(AuthenticationFailedContext context)
        //{
        //    return Task.CompletedTask;
        //}
    }
}
